<template>
  <div class="login-page">
    <div class="container" :class="{ 'right-panel-active': isRegister }">
      <!-- 登录表单 -->
      <div class="container__form container--signin">
        <form class="form" @submit.prevent="handleLogin">
          <h2 class="form__title">用户登录</h2>
          <input 
            type="text" 
            placeholder="用户名" 
            class="input" 
            v-model="form.username"
            required
          />
          <input 
            type="password" 
            placeholder="密码" 
            class="input" 
            v-model="form.password"
            required
          />
          <a href="#" class="link">忘记密码？</a>
          <button type="submit" class="btn">登 录</button>
        </form>
      </div>

      <!-- 注册表单 -->
      <div class="container__form container--signup">
        <form class="form" @submit.prevent="handleRegister">
          <h2 class="form__title">用户注册</h2>
          <input 
            type="text" 
            placeholder="用户名" 
            class="input" 
            v-model="form.username"
            required
          />
          <input 
            type="password" 
            placeholder="密码" 
            class="input" 
            v-model="form.password"
            required
          />
          <input 
            type="password" 
            placeholder="确认密码" 
            class="input" 
            v-model="form.confirmPassword"
            required
          />
          <input 
            type="tel" 
            placeholder="手机号码" 
            class="input" 
            v-model="form.phone"
            required
          />
          <input 
            type="email" 
            placeholder="电子邮箱" 
            class="input" 
            v-model="form.email"
            required
          />
          <button type="submit" class="btn">注 册</button>
        </form>
      </div>

      <!-- 覆盖层 -->
      <div class="container__overlay">
        <div class="overlay">
          <div class="overlay__panel overlay--left">
            <h1>欢迎回来！</h1>
            <p>请使用您的账号登录，继续访问生鲜供应链系统</p>
            <button class="btn ghost" @click="toggleMode">登 录</button>
          </div>
          <div class="overlay__panel overlay--right">
            <h1>你好，朋友！</h1>
            <p>开始注册，加入我们的生鲜供应链系统</p>
            <button class="btn ghost" @click="toggleMode">注 册</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import axios from 'axios'

const router = useRouter()
const userStore = useUserStore()
const isRegister = ref(false)

const form = ref({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: '',
  role: 'customer'
})

// 表单验证函数
const validateForm = () => {
  const { username, password, confirmPassword, phone, email } = form.value
  
  if (!username || username.length < 3) {
    ElMessage.error('用户名至少需要3个字符')
    return false
  }
  
  if (!password || password.length < 6) {
    ElMessage.error('密码至少需要6个字符')
    return false
  }
  
  if (isRegister.value) {
    if (password !== confirmPassword) {
      ElMessage.error('两次输入的密码不一致')
      return false
    }
    
    if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
      ElMessage.error('请输入正确的手机号码')
      return false
    }
    
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      ElMessage.error('请输入正确的电子邮箱')
      return false
    }
  }
  
  return true
}

// 处理登录
const handleLogin = async () => {
  if (!validateForm()) return
  
  try {
    const response = await axios.post('/api/token/', {
      username: form.value.username,
      password: form.value.password
    })

    if (response.data && response.data.access) {
      // 保存token
      userStore.setToken(response.data.access)
      
      // 获取用户信息
      const userResponse = await axios.get('/api/users/profile/', {
        headers: {
          'Authorization': `Bearer ${response.data.access}`
        }
      })
      
      // 保存用户信息
      userStore.setUser(userResponse.data)
    
      // 根据用户角色跳转
      const rolePathMap = {
        customer: '/customer/products',
        purchaser: '/purchaser/dashboard',
        salesman: '/salesman/dashboard',
        deliveryman: '/deliveryman/dashboard',
        admin: '/admin/dashboard',
        delivery_admin: '/delivery_admin/dashboard'
      }
      
      const redirectPath = rolePathMap[userResponse.data.role] || '/'
      router.push(redirectPath)
      ElMessage.success('登录成功')
    }
  } catch (error) {
    console.error('Login error:', error.response?.data || error.message)
    ElMessage.error('登录失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 处理注册
const handleRegister = async () => {
  if (!validateForm()) return
  
  try {
    const { confirmPassword, ...registerData } = form.value
    const response = await axios.post('/api/users/register/', registerData)
    ElMessage.success('注册成功，请登录')
    isRegister.value = false
    form.value = {
      username: registerData.username,
      password: '',
      confirmPassword: '',
      phone: '',
      email: '',
      role: 'customer'
    }
  } catch (error) {
    console.error('Registration error:', error.response?.data || error.message)
    ElMessage.error('注册失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 切换登录/注册模式
const toggleMode = () => {
  isRegister.value = !isRegister.value
  form.value = {
    username: '',
    password: '',
    confirmPassword: '',
    phone: '',
    email: '',
    role: 'customer'
  }
}
</script>

<style>
@import '@/assets/styles/login.css';
</style>